package sel.me.spring.boot159.web.exception;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import sel.me.spring.boot159.web.domain.Result;

import javax.servlet.http.HttpServletResponse;

/**
 * ExceptionHandler.java
 *
 * @author enlu.shen 06/11/2017
 */
@ControllerAdvice
public class ExceptionHandler {


    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandler.class);

    @Value("${spring.application.name}")
    private String appName;


    @org.springframework.web.bind.annotation.ExceptionHandler(value = Throwable.class)
    @ResponseBody
    public Result handle(Throwable e, HttpServletResponse response) {
        Result result = new Result();

        result.setCauseApp(appName);
        /*
         * 参数校验异常
         */
        if (e instanceof IllegalArgumentException
        		|| e instanceof MethodArgumentNotValidException) {
            result.setCode(String.valueOf(UnifyStrErrorCode.PARAM_ERROR.getErrorCode()));
            result.setMsg(UnifyStrErrorCode.PARAM_ERROR.getErrorMsg() + "：" + e.getLocalizedMessage());
            return result;
        }

        
        /*
         * 主动抛出的异常
         */
        if (e instanceof UnifyRuntimeStrException) {
//        	if(! (e instanceof UnLoginException) ) {
//                LOGGER.error("server exception", e);
//        	}
        	UnifyRuntimeStrException basicRuntimeException = (UnifyRuntimeStrException) e;
        	UnifyStrErrorCode errorCode = basicRuntimeException.getErrorCode();
            result.setCode(errorCode.getErrorCode());
            result.setMsg(e.getMessage());
            return result;
        }

        /*
         * 未捕获的异常(意料之外)
         */
        LOGGER.error("server exception", e);
        result.setCode(String.valueOf(UnifyStrErrorCode.COMMON_ERROR.getErrorCode()));
        result.setMsg(UnifyStrErrorCode.COMMON_ERROR.getErrorMsg());
        return result;
    }
}
